<template>
  <view class="common pos-r changePhone">
    <view class="pos-a z-0 wp-100" :class="env === 'H5' ? 'bg-yel' : 'bg-lg'" :style="globalData.barStyle" />
    <u-navbar :fixed="false">
      <u-icon slot="left" name="arrow-left" :color="env === 'H5' ? '#fff' : '#000'" size="19" @tap="navigateBack" />
      <view slot="center" :class="env === 'H5' ? 'c-fff' : 'c-bla'">修改手机号</view>
    </u-navbar>
    <view class="main">
      <view class="content bg-gry">
        <view class="h-a bg-whi">
          <view class="d-f pv-12 ph-24">
            <view class="c-666 fs-30 lh-72 w-140">新手机号</view>
            <u--input v-model="newPhone" placeholder="请输入新手机号" border="false" class="wc-280" maxlength="11" type="number" />
          </view>
          <view class="bdb" />
          <view class="d-f pv-12 ph-24">
            <view class="c-666 fs-30 lh-72 w-140">验证码</view>
            <u--input v-model="verificationCode" placeholder="请输入验证码" border="false" class="wc-280" maxlength="6" type="number" />
            <view class="c-yel fs-28 lh-72 w-160" :class="{ grayLabel: isCountingDown }" @tap="sendVerificationCode">{{ isCountingDown ? `${countdown}秒后重发` : '获取验证码' }}</view>
          </view>
          <view class="bdb" />
        </view>
        <view class="c-999 fs-24 p-24">手机号是登录软件的唯一凭证，当您修改手机号后，需使用新手机号登录软件。</view>
      </view>
      <view class="footer">
        <u-button type="primary" text="确认修改" @tap="changePhone" shape="circle" color="#FEA20D" :throttleTime="2000" />
      </view>
    </view>
  </view>
</template>

<script>
import commonMxins from '@/mixins/common.js';

export default {
  mixins: [commonMxins],
  data() {
    return {
      newPhone: '',
      verificationCode: '',
      isCountingDown: false,
      countdown: 60,
      countdownTimer: null
    };
  },
  onUnload() {
    // 清除定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  },
  methods: {
    // 验证手机号格式
    isValidPhone(phone) {
      return /^1[3-9]\d{9}$/.test(phone);
    },

    // 发送验证码
    async sendVerificationCode() {
      if (!this.newPhone) {
        uni.showToast({ title: '请输入新手机号', icon: 'none' });
        return;
      }

      if (!this.isValidPhone(this.newPhone)) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
        return;
      }

      if (this.isCountingDown) return;

      const res = await this.$request({ url: '/app/verifyCode/send', data: { phoneNumber: this.newPhone } });

      if (res.code === 200) {
        uni.showToast({ title: '验证码发送成功', icon: 'success' });
        // todo
        this.verificationCode = res.msg;
        this.startCountdown();
      } else {
        uni.showToast({ title: res.msg || '验证码发送失败', icon: 'none' });
      }
    },

    // 开始倒计时
    startCountdown() {
      this.isCountingDown = true;
      this.countdown = 60;

      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
      }

      this.countdownTimer = setInterval(() => {
        if (this.countdown <= 1) {
          clearInterval(this.countdownTimer);
          this.isCountingDown = false;
          this.countdown = 60;
        } else {
          this.countdown--;
        }
      }, 1000);
    },

    // 修改手机号
    async changePhone() {
      if (!this.newPhone) {
        uni.showToast({ title: '请输入新手机号', icon: 'none' });
        return;
      }

      if (!this.isValidPhone(this.newPhone)) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
        return;
      }

      if (!this.verificationCode) {
        uni.showToast({ title: '请输入验证码', icon: 'none' });
        return;
      }
      const res = await this.$request({ url: '/app/appUser/bindPhone', data: { phoneNumber: this.newPhone, verifyCode: this.verificationCode }, showLoading: true });

      if (res.code === 200) {
        // 更新storage中的userInfo的phoneNumber
        const storedUserInfo = uni.getStorageSync('userInfo');
        if (storedUserInfo) {
          const userInfo = typeof storedUserInfo === 'string' ? JSON.parse(storedUserInfo) : storedUserInfo;
          userInfo.phoneNumber = this.newPhone;
          uni.setStorageSync('userInfo', userInfo);
        }
        await this.$async.delay(1000);
        uni.showModal({
          title: '提示',
          content: '手机号已修改成功，请使用新手机号重新登录',
          showCancel: false,
          success: async res => {
            if (res.confirm) {
              await this.$request({ url: '/app/appUser/offline', method: 'POST' });
              this.clearStorage();
              uni.reLaunch({ url: '/pages/global/login/login' });
            }
          }
        });
      } else {
        uni.showToast({ title: res.msg || '手机号修改失败', icon: 'none' });
      }
    }
  }
};
</script>

<style scoped lang="scss">
.changePhone {
  .main {
    .content {
      height: calc(100% - 67px);
    }
  }
}
</style>
